package com.aw.baselib.util;

import static android.view.View.DRAWING_CACHE_QUALITY_HIGH;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Environment;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.aw.baselib.R;
import com.aw.baselib.bean.CommonImgItemBean;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author : hzw.
 */

public class AwImgUtil {

    /**
     * 自定义默认加载中及失败后的图片
     *
     * @param mContext
     * @param v
     * @param url
     * @param resId
     */
    public static void setImgWithCustom(Context mContext, ImageView v, Object url, int resId) {
        Glide.with(mContext).
                asBitmap().
                load(url).
                placeholder(resId).
                error(resId).
                into(v);
    }


    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url icon_img_load_error
     */
    public static void setImgNoPlace(Context mContext, ImageView v, Object url) {
        Glide.with(mContext).
                asBitmap().
                load(url).
                into(v);
    }


    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url icon_img_load_error
     */
    public static void setImgDefaultVehicle(Context mContext, ImageView v, Object url) {
        Glide.with(mContext).
                asBitmap().
                load(url).
                //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                        into(v);
    }

    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url icon_img_load_error
     */
    public static void setImg(Context mContext, ImageView v, Object url) {
        Glide.with(mContext).
                asBitmap().
                load(url).
                //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                        into(v);
    }


    /**
     * 原尺寸展示
     * @param mContext
     * @param v
     * @param url
     */
    public static void setImgOriginal(Context mContext, ImageView v, Object url) {
        Glide.with(mContext).
                asBitmap().
                override(ViewGroup.LayoutParams.MATCH_PARENT, Target.SIZE_ORIGINAL).
                load(url).
                //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                        into(v);
    }

    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url icon_img_load_error
     */
    public static void setImgNoCache(Context mContext, ImageView v, Object url) {
        Glide.with(mContext).
                asBitmap().
                load(url).
                skipMemoryCache(true). // 不使用内存缓存
                diskCacheStrategy(DiskCacheStrategy.NONE). // 不使用磁盘缓存
                //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                        into(v);
    }

    public static void setImg(Context mContext, ImageView v, int defaultRes, Object url) {
        Glide.with(mContext).
                asBitmap().
                load(url).
                placeholder(mContext.getResources().getDrawable(defaultRes)).
                error(mContext.getResources().getDrawable(defaultRes)).
                into(v);
    }

    public static void setImgGif(Context context, ImageView iv, Object url) {
        Glide.with(context).
                load(url).
                into(iv);
    }

    public static boolean isGif(String localPath) {
        try {
            FileInputStream inputStream = new FileInputStream(localPath);
            int[] flags = new int[5];
            flags[0] = inputStream.read();
            flags[1] = inputStream.read();
            flags[2] = inputStream.read();
            flags[3] = inputStream.read();
            inputStream.skip(inputStream.available() - 1);
            flags[4] = inputStream.read();
            inputStream.close();
            return flags[0] == 71 && flags[1] == 73 && flags[2] == 70 && flags[3] == 56 && flags[4] == 0x3B;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 设置圆角图片
     * @param mContext
     * @param v
     * @param url
     * @param defaultCornor
     */
    public static void setImgRound(Context mContext, ImageView v, Object url, int defaultCornor) {
        //Glide设置图片圆角角度
        RoundedCorners roundedCorners = new RoundedCorners(defaultCornor);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        // RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(20, 20);
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
        Glide.with(mContext).
                asBitmap().
                load(url).
                //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_load_ing)).
                //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                        apply(options).
                into(v);
    }

    /**
     * 设置圆角头像图片
     * @param mContext
     * @param v
     * @param url
     * @param defaultCornor
     * @param defaultImgId
     */
    public static void setImgRoundAvatar(Context mContext, ImageView v, Object url, int defaultCornor, int defaultImgId) {
        //Glide设置图片圆角角度
        RoundedCorners roundedCorners = new RoundedCorners(defaultCornor);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        // RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(20, 20);
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
        Glide.with(mContext).
                asBitmap().
                load(url).
                placeholder(mContext.getResources().getDrawable(defaultImgId == -1 ? R.drawable.iv_head : defaultImgId)).
                error(mContext.getResources().getDrawable(defaultImgId == -1 ? R.drawable.iv_head : defaultImgId)).
                apply(options).
                into(v);
    }

    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url
     */
    public static void setImgApp(Context mContext, ImageView v, Object url) {
        Glide.with(mContext).
                asBitmap().
                load(url).
                //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_load_ing)).
                //                error(mContext.getResources().getDrawable(R.mipmap.bg_video)).
                //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                        into(v);
    }

    /**
     * 默认头像加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url
     */
    public static void setImgAvatar(Context mContext, ImageView v, Object url) {
        Glide.with(mContext).
                asBitmap().
                load(url).
                placeholder(mContext.getResources().getDrawable(R.drawable.iv_head)).
                error(mContext.getResources().getDrawable(R.drawable.iv_head)).
                into(v);
    }

    /**
     * 回调监听图片加载, 使用默认头像加载及失败图片
     *
     * @param mContext
     * @param target
     * @param url
     */
    public static void setImgToTarget(Context mContext, SimpleTarget<Bitmap> target, Object url) {
        Glide.with(mContext).
                asBitmap().
                load(url).
                //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_load_ing)).
                //                error(mContext.getResources().getDrawable(R.drawable.icon_img_load_error)).
                        into(target);
    }

    public static void setImgVideoFirst(Context mContext, ImageView v, String url) {
        if(AwDataUtil.isEmpty(url)) {
            Glide.with(mContext).
                    asBitmap().
                    load(url).
                    //                    placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_load_ing)).
                    //                    error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                            into(v);
        } else {
            Glide.with(mContext).
                    asBitmap().
                    load(getBitmapFormUrl(url)).
                    placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_load_ing)).
                    //                    error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
                            into(v);
        }

    }


    /**
     * drawable to bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * drawable to bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap2(Drawable drawable) {
        BitmapDrawable bd = (BitmapDrawable) drawable;
        return bd.getBitmap();
    }

    /**
     * 将彩色图转换为灰度图
     *
     * @param img 位图
     * @return 返回转换好的位图
     */
    public static Bitmap convertGreyImg(Bitmap img) {
        int width = img.getWidth();         //获取位图的宽
        int height = img.getHeight();       //获取位图的高

        int[] pixels = new int[width * height]; //通过位图的大小创建像素点数组

        img.getPixels(pixels, 0, width, 0, 0, width, height);
        int alpha = 0xFF << 24;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int grey = pixels[width * i + j];

                int red = ((grey & 0x00FF0000) >> 16);
                int green = ((grey & 0x0000FF00) >> 8);
                int blue = (grey & 0x000000FF);

                grey = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
                grey = alpha | (grey << 16) | (grey << 8) | grey;
                pixels[width * i + j] = grey;
            }
        }
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        result.setPixels(pixels, 0, width, 0, 0, width, height);
        return result;
    }

    /**
     * 灰度处理
     *
     * @param bmSrc
     * @return
     */
    public static Bitmap bitmap2Gray(Bitmap bmSrc) {
        // 得到图片的长和宽
        int width = bmSrc.getWidth();
        int height = bmSrc.getHeight();
        // 创建目标灰度图像
        Bitmap bmpGray = null;
        bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        // 创建画布
        Canvas c = new Canvas(bmpGray);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmSrc, 0, 0, paint);
        return bmpGray;
    }

    /**
     * 左1右2上3下4
     */
    public static void setDrawableDirection(Context context, TextView tv, int tag, int resId) {
        Drawable drawable = context.getResources().getDrawable(resId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        switch (tag) {
            case 1:
                tv.setCompoundDrawables(drawable, null, null, null);
                break;
            case 2:
                tv.setCompoundDrawables(null, null, drawable, null);
                break;
            case 3:
                tv.setCompoundDrawables(null, drawable, null, null);
                break;
            case 4:
                tv.setCompoundDrawables(null, null, null, drawable);
                break;
        }
    }

    public static void cancelDrawableDirection(Context context, TextView tv) {
        tv.setCompoundDrawables(null, null, null, null);
    }

    /**
     * https://blog.csdn.net/oAiTan/article/details/50517629
     * 某些机型直接获取会为null,在这里处理一下防止国内某些机型返回null
     */
    public static Bitmap getViewBitmap(View view) {
        if (view == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }

    /**
     *把View转换成Bitmap类型
     *@paramaddViewContent要转换的View
     *@return
     */
    public static Bitmap getViewBitmapFromLayout(View view) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(DRAWING_CACHE_QUALITY_HIGH);
        view.measure(
                View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED));
        view.layout(0,0,
                view.getMeasuredWidth(),
                view.getMeasuredHeight());



        view.buildDrawingCache();
        Bitmap cacheBitmap = view.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        return bitmap;
    }

    public static Bitmap getBitmapFromImageView(ImageView imageView) {
        return ((BitmapDrawable)imageView.getDrawable()).getBitmap();
    }

    public static Bitmap getBitmapFormUrl(String url) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            if (Build.VERSION.SDK_INT >= 14) {
                retriever.setDataSource(url, new HashMap<String, String>());

            } else {
                retriever.setDataSource(url);

            }

            /*getFrameAtTime()--->在setDataSource()之后调用此方法。 如果可能，该方法在任何时间位置找到代表性的帧，         并将其作为位图返回。这对于生成输入数据源的缩略图很有用。**/

            bitmap = retriever.getFrameAtTime();

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (IllegalArgumentException | IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    public static void setImgFromBase64(ImageView iv, String base64Str) {
        if(AwDataUtil.isEmpty(base64Str) || iv == null) {
            return;
        }
        byte[] decode = Base64.decode(base64Str.split(",")[1], Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        iv.setImageBitmap(bitmap);
    }

    public static Bitmap getBitmapByResId(Context context,int vectorDrawableId) {
        Bitmap bitmap=null;
        if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
            Drawable vectorDrawable = context.getDrawable(vectorDrawableId);
            bitmap = AwBitmapUtils.getBitmapFromVectorDrawable(context,vectorDrawable);
        }else {
            bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId);
        }
        return bitmap;
    }

    public static void savePicture(Bitmap bm, String fileName) {
        if (null == bm) {
            AwLog.d("savePicture: ------------------图片为空------");
            return;
        }
        File foder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/grainimage");
        AwLog.d("savePicture path: " + foder.getAbsolutePath());
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            //压缩保存到本地
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        AwToastUtil.show("生成图片成功!");
    }

    /**
     * <P>标签内是否全是图片类型标签</P>
     * @param html
     * @return
     */
    public static boolean isParagraphOnlyImages(String html) {
        if(AwDataUtil.isEmpty(html) || !html.contains("img")) {
            return false;
        }
        String tempStr = html.substring(html.indexOf(">") + 1);
        AwLog.d("isParagraphOnlyImages tempStr: " + tempStr);
        if(!tempStr.startsWith("<img")) {
            return false;
        }
        // 正则表达式匹配<p>标签内的内容，确保其中只包含<img>标签
        Pattern pattern = Pattern.compile("<p[^>]*>(<img[^>]+>)+</p>");
        Matcher matcher = pattern.matcher(html);

        // 遍历所有匹配项，检查每个<p>标签是否满足条件
        while (matcher.find()) {
            String paragraph = matcher.group();
            // 如果paragraph不匹配，则跳出循环
            if (!pattern.matcher(paragraph).matches()) {
                return false;
            }
        }
        return true;
    }

    public static List<CommonImgItemBean> getAllImgUrlList(String html) {
        List<CommonImgItemBean> list = new ArrayList<>();
        // 定义正则表达式，用于匹配被双引号包围的文本
        Pattern pattern = Pattern.compile("\"(.*?)\"");
        //        Pattern pattern = Pattern.compile("\"([^\"]+)\"");
        Matcher matcher = pattern.matcher(html);

        // 创建一个列表用于保存提取的内容

        // 使用while循环查找所有匹配的字符串
        while (matcher.find()) {
            // 获取匹配的字符串并将其添加到列表中
            list.add(new CommonImgItemBean(matcher.group(1)));
        }
        return list;
    }
}
